package blip.jcaf.cm;

import java.io.IOException;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

public class AsyncConnection extends Observable implements Runnable {

	private String url;

	public AsyncConnection(String url, Observer obs) {
		this.url = url;
		this.addObserver(obs);
	}
	
	@Override
	public void run() {
		boolean changed = true;
		while (true) {

			Map<?, ?> reply = null;
			try {
				reply = RestClient.connect(url);
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			
			String location = "Device not detected...";
			if (reply.get("location") != null) {
				location = (String) reply.get("location");
				setChanged();
				notifyObservers(location);
				changed = true;
			} else {
				if(changed == true) {
					System.out.println("Device not detected...");
					changed = false;
					location = "toBeDefined";
					setChanged();
					notifyObservers(location);
				}
			}

			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
